const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database().collection("user");

// 获取openId云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const oldPassword = event.oldPassword
  const newPassword = event.newPassword
  if(oldPassword == null || newPassword == null)
  {
    return {
      code:400,
      data:{},
      msg:"empty param"
    }
  }
  else
  {
    console.log(newPassword.length)
    if(newPassword.length < 8 || newPassword.length > 16)
    {
      return {
        code:400,
        data:{},
        msg:"wrong param"
      }
    }
    const res = await db.where({openid:wxContext.OPENID,password:oldPassword}).get()
    if(res.data.length == 0)
    {
      return {
        code:400,
        data:{},
        msg:"wrong old password"
      }
    }
    const result = await db.doc(res.data[0]._id).update({data:{
      password:newPassword,
    }})
    let updated = result.stats.updated
    if(updated == 0)
    {
        return {
          code:404,
          data:{
            updated:updated
          },
          msg:"Old password is same as new password!"
        }
    }
    else
    {
      return {
        code:200,
        data:{
          updated:updated
        },
        msg:"success"
      }
    }
  }
};
